package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"soft-manage/cache"
	"soft-manage/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	num, _ := strconv.Atoi(c.PostForm("num"))

	data := models.Good{
		Name: name,
		Num:  num,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return
}
func List(c *gin.Context) {
	gid, _ := strconv.Atoi(c.PostForm("gid"))
	/*
			SELECT
		  *
		FROM
		  goods
		  LEFT JOIN types ON goods.id = types.gid
	*/
	var good []models.Good
	models.DB.Table("goods").
		Joins("LEFT JOIN types ON goods.id = types.gid").
		Where("goods.id=?", gid).Find(&good)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": good,
	})
	return
}
func GoodAddTypes(c *gin.Context) {
	tid, _ := strconv.Atoi(c.PostForm("tid"))
	gid, _ := strconv.Atoi(c.PostForm("gid"))

	data := models.GoodTypes{
		Gid: gid,
		Tid: tid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return
}
func TypesList(c *gin.Context) {
	var types []models.Types
	redis_key := "types_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&types)
		jsonData, _ := json.Marshal(types)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &types)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": types,
	})
	return
}
func GoodList(c *gin.Context) {
	var types []models.Types
	redis_key := "types_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&types)
		jsonData, _ := json.Marshal(types)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &types)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": types,
	})
	return
}
